// This is the main DLL file.

#include "stdafx.h"

#include "PreStiParallelPortLibrary.h"

int cz::zcu::PreSti::ParallelPortLibrary::write(unsigned char data, unsigned char port)
{
	HANDLE              hndFile;
	BOOL    IoctlResult;
	ULONG               ReturnedLength;
	UCHAR				buffer[2];
	LPCWSTR				LPT1 = L"LPT1:";
	LPCWSTR				LPT2 = L"LPT2:";
	LPCWSTR				LPT3 = L"LPT3:";
	LPCWSTR				LPT;
	if(port == NULL) port = 1;
	switch(port) {
		case 1: LPT = LPT1; break;
		case 2: LPT = LPT2; break;
		case 3: LPT = LPT3;
	}
	hndFile = CreateFile(LPT, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
	if(hndFile == INVALID_HANDLE_VALUE) {
		return -1; //LPT port is not present
	}
	CloseHandle(hndFile);

	hndFile = CreateFile(L"\\\\.\\GpdDev", // device name
		GENERIC_READ|GENERIC_WRITE,
		FILE_SHARE_WRITE,
		NULL,
		OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL,
		NULL);
	if(hndFile == INVALID_HANDLE_VALUE) {
		return -2; //PreSti Parallel Port Driver is not insalled
	}
	buffer[0] = port;
	buffer[1] = data;
	IoctlResult = DeviceIoControl(
                        hndFile,                // Handle to device
                        IOCTL_PRESTI_SEND_BYTE,              // IO Control code for Write
                        buffer,           // Buffer to driver.  Holds port & data.
                        2,             // Length of buffer in bytes.
                        NULL,                   // Buffer from driver.   Not used.
                        0,                      // Length of buffer in bytes.
                        &ReturnedLength,        // Bytes placed in outbuf.  Should be 0.
                        NULL                    // NULL means wait till I/O completes.
                        );
	CloseHandle(hndFile);
	if (!IoctlResult)                            // Did the IOCTL succeed?
	{
		return -3; //Cannot write to parallel port
	}
	return 0;
}
